package com.example.teemor.es_demo.controller;

import com.example.teemor.es_demo.entity.Order;
import com.example.teemor.es_demo.entity.OrderItem;
import com.example.teemor.es_demo.service.OrderService;
import com.example.teemor.es_demo.service.UserBehaviorService;
import com.example.teemor.es_demo.controller.UserController.ApiResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/client/orders")
@RequiredArgsConstructor
public class OrderController {

    private final OrderService orderService;
    private final UserBehaviorService userBehaviorService;

    /**
     * 创建订单
     */
    @PostMapping
    public ResponseEntity<ApiResponse<Order>> createOrder(
            @RequestParam Long userId,
            @Valid @RequestBody List<OrderItem> orderItems,
            HttpServletRequest request) {
        try {
            Order order = orderService.createOrder(userId, orderItems);
            
            // 记录订单创建行为
            userBehaviorService.recordPageView(userId, request.getSession().getId(), 
                    "/api/orders/create", request);
            
            return ResponseEntity.ok(ApiResponse.success(order, "订单创建成功"));
        } catch (Exception e) {
            log.error("Failed to create order for user: {}", userId, e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 根据ID获取订单
     */
    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<Order>> getOrderById(@PathVariable Long id,
                                                          HttpServletRequest request) {
        try {
            Order order = orderService.getOrderById(id)
                    .orElseThrow(() -> new RuntimeException("订单不存在"));
            
            // 记录订单查看行为
            userBehaviorService.recordPageView(order.getUser().getId(), 
                    request.getSession().getId(), "/api/orders/" + id, request);
            
            return ResponseEntity.ok(ApiResponse.success(order, "获取订单成功"));
        } catch (Exception e) {
            log.error("Failed to get order by id: {}", id, e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 根据订单号获取订单
     */
    @GetMapping("/order-no/{orderNo}")
    public ResponseEntity<ApiResponse<Order>> getOrderByOrderNo(@PathVariable String orderNo) {
        try {
            Order order = orderService.getOrderByOrderNo(orderNo)
                    .orElseThrow(() -> new RuntimeException("订单不存在"));
            return ResponseEntity.ok(ApiResponse.success(order, "获取订单成功"));
        } catch (Exception e) {
            log.error("Failed to get order by order no: {}", orderNo, e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 获取用户订单列表
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<ApiResponse<Page<Order>>> getUserOrders(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            HttpServletRequest request) {
        try {
            Pageable pageable = PageRequest.of(page, size);
            Page<Order> orders = orderService.getUserOrders(userId, pageable);
            
            // 记录用户订单查看行为
            userBehaviorService.recordPageView(userId, request.getSession().getId(), 
                    "/api/orders/user/" + userId, request);
            
            return ResponseEntity.ok(ApiResponse.success(orders, "获取用户订单成功"));
        } catch (Exception e) {
            log.error("Failed to get user orders for user: {}", userId, e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 获取用户指定状态的订单
     */
    @GetMapping("/user/{userId}/status/{status}")
    public ResponseEntity<ApiResponse<List<Order>>> getUserOrdersByStatus(
            @PathVariable Long userId,
            @PathVariable Order.OrderStatus status) {
        try {
            List<Order> orders = orderService.getUserOrdersByStatus(userId, status);
            return ResponseEntity.ok(ApiResponse.success(orders, "获取用户订单成功"));
        } catch (Exception e) {
            log.error("Failed to get user orders by status for user: {}, status: {}", userId, status, e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }



    /**
     * 取消订单
     */
    @PutMapping("/{id}/cancel")
    public ResponseEntity<ApiResponse<Order>> cancelOrder(@PathVariable Long id) {
        try {
            Order order = orderService.cancelOrder(id);
            return ResponseEntity.ok(ApiResponse.success(order, "订单取消成功"));
        } catch (Exception e) {
            log.error("Failed to cancel order: {}", id, e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }





    /**
     * 获取用户订单统计
     */
    @GetMapping("/user/{userId}/stats")
    public ResponseEntity<ApiResponse<OrderService.UserOrderStats>> getUserOrderStats(
            @PathVariable Long userId) {
        try {
            OrderService.UserOrderStats stats = orderService.getUserOrderStats(userId);
            return ResponseEntity.ok(ApiResponse.success(stats, "获取用户订单统计成功"));
        } catch (Exception e) {
            log.error("Failed to get user order stats for user: {}", userId, e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }



    /**
     * 获取订单状态枚举
     */
    @GetMapping("/status-options")
    public ResponseEntity<ApiResponse<Order.OrderStatus[]>> getOrderStatusOptions() {
        try {
            Order.OrderStatus[] statuses = Order.OrderStatus.values();
            return ResponseEntity.ok(ApiResponse.success(statuses, "获取订单状态选项成功"));
        } catch (Exception e) {
            log.error("Failed to get order status options", e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 订单支付
     */
    @PostMapping("/{id}/pay")
    public ResponseEntity<ApiResponse<Order>> payOrder(@PathVariable Long id,
                                                      HttpServletRequest request) {
        try {
            Order order = orderService.updateOrderStatus(id, Order.OrderStatus.PAID);
            
            // 记录支付行为
            userBehaviorService.recordPageView(order.getUser().getId(), 
                    request.getSession().getId(), "/api/orders/" + id + "/pay", request);
            
            return ResponseEntity.ok(ApiResponse.success(order, "订单支付成功"));
        } catch (Exception e) {
            log.error("Failed to pay order: {}", id, e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }



    /**
     * 订单确认收货
     */
    @PostMapping("/{id}/deliver")
    public ResponseEntity<ApiResponse<Order>> deliverOrder(@PathVariable Long id) {
        try {
            Order order = orderService.updateOrderStatus(id, Order.OrderStatus.DELIVERED);
            return ResponseEntity.ok(ApiResponse.success(order, "订单确认收货成功"));
        } catch (Exception e) {
            log.error("Failed to deliver order: {}", id, e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }
}